﻿
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Domain.Entities;
using ProduceBasicData.Infrastructure.Interface;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ProduceBasicData.Infrastructure.Implement
{
    public class BaseRespository<T> : IBaseRespository<T> where T : BaseEntity
    {
        private readonly MyDBContext context;

        public BaseRespository(MyDBContext context)
        {
            this.context = context;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T t)
        {
            await context.Set<T>().AddAsync(t);
            return await context.SaveChangesAsync();
        }

        /// <summary>
        /// 新增并获取Id
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAndGetIdAsync(T entity)
        {
            await context.Set<T>().AddAsync(entity);
            await context.SaveChangesAsync();
            // 假设实体有自增主键属性“Id”
            return (int)(typeof(T).GetProperty("Id")?.GetValue(entity) ?? 0);
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> AddRangeAsync(List<T> t)
        {
            await context.Set<T>().AddRangeAsync(t);
            return await context.SaveChangesAsync();
        }
        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return context.Set<T>();
        }
        /// <summary>
        /// 异步查询 - 获取所有实体列表
        /// </summary>
        /// <returns>所有实体列表</returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await context.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 获取单条数据根据条件查询
        /// </summary>
        /// <returns></returns>
        public async Task<T> GetFirstOrDefaultAsync()
        {
            // 返回集合中的第一条数据
            return await context.Set<T>().FirstOrDefaultAsync();
        }
        
        /// <summary>
        /// 根据条件查询单条数据
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <returns>符合条件的实体或null</returns>
        public async Task<T> GetFirstOrDefaultAsync(Expression<Func<T, bool>> predicate)
        {
            return await context.Set<T>().FirstOrDefaultAsync(predicate);
        }
        /// <summary>
        /// 根据条件查询集合（新增实现）
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <returns>符合条件的实体列表</returns>
        public async Task<List<T>> GetAllAsync(Expression<Func<T, bool>> predicate)
        {
            return await context.Set<T>().Where(predicate).ToListAsync();
        }

        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await context.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 根据条件查询返回集合
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<List<T>> GetRangeAsync(int[] ids)
        {
            return await context.Set<T>().Where(t => ids.Contains(t.Id)).ToListAsync();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public Task<int> Update(T t)
        {
            context.Set<T>().Update(t);
            return context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<int> UpdateRange(IList<T> t)
        {
            context.Set<T>().UpdateRange(t);
            return await context.SaveChangesAsync();
        }




        // 新增：仅添加，不保存
        public async Task AddNoSaveAsync(T t)
        {
            await context.Set<T>().AddAsync(t);
            // 不调用SaveChangesAsync，仅跟踪状态
        }

        // 新增：仅批量添加，不保存
        public async Task AddRangeNoSaveAsync(List<T> t)
        {
            await context.Set<T>().AddRangeAsync(t);
            // 不调用SaveChangesAsync
        }

        // 新增：仅更新，不保存
        public void UpdateNoSave(T t)
        {
            context.Set<T>().Update(t);
            // 不调用SaveChangesAsync
        }

        // 新增：仅批量更新，不保存
        public void UpdateRangeNoSave(IList<T> t)
        {
            context.Set<T>().UpdateRange(t);
            // 不调用SaveChangesAsync
        }

        // 新增：手动保存（供事务内统一调用）
        public async Task<int> SaveChangesAsync()
        {
            return await context.SaveChangesAsync();
        }

        public MyDBContext DB => context;
        /// <summary>
        /// 检查是否存在符合条件的实体
        /// </summary>
        public async Task<bool> AnyAsync(Expression<Func<T, bool>> predicate)
        {
            return await context.Set<T>().AnyAsync(predicate);
        }
    }
}
